package com.crazy.spring;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Zhu Dunfeng
 * @date 2022/4/26 14:12
 */
public class DefaultBeanProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        Class<?>[] interfaces = bean.getClass().getInterfaces();
        //使用JDK接口动态代理
        if (interfaces.length > 0) {
            Object instance = Proxy.newProxyInstance(DefaultBeanProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //System.out.println("切面逻辑");
                    return method.invoke(bean, args);
                }
            });
            return instance;
        } else {
            //使用Cglib类动态代理
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    //System.out.println("前置通知");
                    Object instance = methodProxy.invokeSuper(o, objects);
                    //System.out.println("后置通知");
                    return instance;
                }
            });
            return enhancer.create();
        }
    }
}
